package com.hello.facerecognition;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.google.gson.Gson;
import com.hello.facerecognition.Application.BaseApplication;
import com.hello.facerecognition.com.hello.utils.StringUtils;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class RegisterActivity extends Activity implements View.OnClickListener {
    public static final Integer Request_Code = 1000;

    @InjectView(R.id.cv_add)
    CardView cvAdd;

    @InjectView(R.id.et_image)
    EditText image;

    @InjectView(R.id.button6)
    Button selectImage;

    @InjectView(R.id.bt_go)
    Button register;

    @InjectView(R.id.et_image)
    EditText img;

    @InjectView(R.id.et_name)
    EditText et_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.inject(this);
        setEditTextReadOnly(image);
        selectImage.setOnClickListener(this);
        register.setOnClickListener(this);
    }


    @SuppressLint("ResourceAsColor")
    public static void setEditTextReadOnly(TextView view){
        view.setTextColor(R.color.black_overlay);   //设置只读时的文字颜色
        if (view instanceof android.widget.EditText){
            view.setCursorVisible(false);      //设置输入框中的光标不可见
            view.setFocusable(false);           //无焦点
            view.setFocusableInTouchMode(false);     //触摸时也得不到焦点
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button6:{
                if (ActivityCompat.checkSelfPermission(BaseApplication.context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //未获得，向用户请求
                    Log.d("No permission: ", "开始请求权限");
                    ActivityCompat.requestPermissions(this, new String[]
                            {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
                } else {
                    Intent intent = new Intent(this, Photo.class);
                    startActivityForResult(intent,Request_Code);
                }
                break;
            }
            case R.id.bt_go:{
                String file_path = img.getText().toString().trim();
                String name = et_name.getText().toString().trim();
                if(StringUtils.isNullOrEmpty(file_path) || StringUtils.isNullOrEmpty(name)){
                    showFailRegister(R.drawable.sorry,"无法提交","请完整填写信息");
                }else {
                    Object[] objects = new Object[]{file_path,name};
                    Register register1 = new Register();
                    register1.execute(objects);
                }
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if(data != null) {
            if (requestCode == Request_Code) {
                String file_path = data.getStringExtra("file_path");
                Log.d("Path:", file_path);
                if (StringUtils.isNullOrEmpty(file_path)) {
                    showMultiBtnDialog();
                } else {
                    img.setText(file_path);
                }
            }
        }
    }

    private void showMultiBtnDialog(){
        @SuppressWarnings("deprecation")
        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppCompat);
        AlertDialog.Builder normalDialog =
                builder;
        normalDialog.setIcon(R.drawable.sorry);
        normalDialog.setTitle("凉凉").setMessage("图片上传失败，请重试");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // ...To-
                    }
                });
        // 创建实例并显示
        normalDialog.create().show();
    }

    private void showFailRegister(Integer iconId,String title,String message){
        @SuppressWarnings("deprecation")
        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.AppCompat);
        AlertDialog.Builder normalDialog =
                builder;
        normalDialog.setIcon(iconId);
        normalDialog.setTitle(title).setMessage(message);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // ...To-
                    }
                });
        // 创建实例并显示
        normalDialog.create().show();
    }


    public void Register(String file_path,String name){String url = String.format("http://47.92.246.214:9988/register.php?img=%s&user_name=%s",file_path,name);
        Request request = new Request.Builder()
                .url(url)
                .build();
        BaseApplication.okHttpClient.newCall(request).enqueue(new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                RegisterActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        showFailRegister(R.drawable.sorry,"注册失败","服务器错误！");                                }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                RegisterActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        et_name.setText("");
                    }
                });
                String json = response.body().string();
                Log.i("json: ",json);
                if(!StringUtils.isNullOrEmpty(json)){
                    Map<String,String> infoMap = new Gson().fromJson(json,Map.class);
                    System.out.println(infoMap);
                    if(infoMap != null){
                        if(10000 == Double.parseDouble(String.valueOf(infoMap.get("code")))){
                            RegisterActivity.this.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    showFailRegister(R.drawable.success,"注册成功","成功！您可以选择继续注册或者退出页面");
                                }
                            });
                        }else if(10001 == Double.parseDouble(String.valueOf(infoMap.get("code")))){
                            RegisterActivity.this.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    showFailRegister(R.drawable.sorry,"注册失败","在照片里检测不到人脸！");
                                }
                            });
                        }else{
                            RegisterActivity.this.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    showFailRegister(R.drawable.sorry,"注册失败","服务器错误！");                                }
                            });
                        }
                    }else{
                        RegisterActivity.this.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                showFailRegister(R.drawable.sorry,"注册失败","服务器错误！");                                }
                        });
                    }
                }else{
                    RegisterActivity.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            showFailRegister(R.drawable.sorry,"注册失败","服务器错误！");                                }
                    });
                }
            }
        });

    }

    class Register extends AsyncTask {
        public Register(){
            super();
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            final String path = (String) objects[0];
            final String username = (String) objects[1];
            Register(path,username);
            return null;
        }

    }
}
